package LeetCode.offer;

import domain.TreeNode;

import java.util.LinkedList;
import java.util.Stack;

/**
 * @author: leiwenkang
 * @date: 2020/7/10
 * @time: 11:49
 */
public class Test27二叉树的镜像 {

    public static void main(String[] args) {
        LinkedList<Integer> list = new LinkedList<>();
        list.add(0);
        list.add(1);
        list.add(2);
        list.add(3);
        System.out.println(list.remove());

    }

    //方法一 递归
    public TreeNode mirrorTree(TreeNode root) {
        if (root == null) {
            return root;
        }

        Stack<Integer> stack = new Stack<>();
        if (root.left == null && root.right == null) {
            return root;
        }

        //交换其左右孩子
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;

        //递归左子树
        mirrorTree(root.left);
        //递归右子树
        mirrorTree(root.right);

        return root;
    }

    //方法二 非递归
    public TreeNode mirrorTree2(TreeNode root) {
        if (root == null) {
            return root;
        }

        LinkedList<TreeNode> list = new LinkedList<>();
        list.add(root);

        while (!list.isEmpty()) {
            TreeNode node = list.remove();

            if (node.left == null && node.right == null) {
                continue;
            }

            if (node.left != null) {
                list.add(node.left);
            }

            if (node.right != null) {
                list.add(node.right);
            }

            //交换其左右孩子
            TreeNode temp = node.left;
            node.left = node.right;
            node.right = temp;
        }

        return root;
    }
}
